<template>
  <div class="user-search-container">
    <div class="search-form-container">
      <br>
      <div class="search-form">
        <el-form ref="driverForm" :model="driverForm" label-width="80px">
          <el-form-item label="用户姓名">
            <el-input v-model="driverForm.name" @keyup.enter.native="onSubmit"></el-input>
          </el-form-item>

          <el-form-item label="手机号码">
            <el-input v-model="driverForm.phone" @keyup.enter.native="onSubmit"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索用户</el-button>
            <el-button>取消</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="user-info">
        <el-descriptions direction="vertical" :column="4" border>
          <el-descriptions-item label="用户姓名">{{ userObject.userName }}</el-descriptions-item>
          <el-descriptions-item label="手机号码">{{ userObject.userPhone }}</el-descriptions-item>
          <el-descriptions-item label="昵称">{{ userObject.userNick }}</el-descriptions-item>
          <!--          <el-descriptions-item label="头像">{{ userObject.userHeader }}</el-descriptions-item>-->
          <el-descriptions-item label="角色">
            <el-tag v-if="userObject.userRole === 0" type="info">司机</el-tag>
            <el-tag v-else-if="userObject.userRole === 1" type="success">车队长</el-tag>
            <el-tag v-else>未知角色</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="公司名称">{{ userObject.companyName }}</el-descriptions-item>
        </el-descriptions>
<!--        <el-button type="primary" @click="showDialog" v-hasRole="['common']">分配给车队长</el-button>-->
        <el-button type="primary" @click="bindCompanyOnly" v-hasRole="['common']">绑定到公司</el-button>
        <el-button type="primary" @click="bindAgent"  v-hasRole="['dragon']">指定业务员</el-button>
        <el-dialog :visible.sync="dialogVisible" title="请选择车队长" width="50%">

          <el-table v-loading="loading" :data="driverLeaderObject" >
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="用户姓名" align="center" prop="userName"/>
            <el-table-column label="手机号码" align="center" prop="userPhone"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  @click="bindCompany(scope.row)"
                >绑定员工
                </el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-dialog>
      </div>s
      <br>
    </div>

    <div class="driver-list">
      <br>
      <el-table v-loading="loading" :data="userList">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="手机号码" align="center" prop="userPhone"/>
        <el-table-column label="微信昵称" align="center" prop="userNick"/>
        <el-table-column label="微信头像" align="center" prop="userHeader" width="100">
          <template slot-scope="scope">
            <image-preview :src="scope.row.userHeader" :width="50" :height="50"/>
          </template>
        </el-table-column>
        <el-table-column label="用户姓名" align="center" prop="userName"/>
        <el-table-column label="司机角色" align="center" prop="userRole">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.c_user_role" :value="scope.row.userRole"/>
          </template>
        </el-table-column>
        <el-table-column label="公司名称" align="center" prop="companyName"/>
        <!--      <el-table-column label="车辆id编号" align="center" prop="carId" />-->
        <!--      <el-table-column label="个人钱包id编号" align="center" prop="walletPersonId" />-->
        <!--      <el-table-column label="公司钱包id编号" align="center" prop="walletCompnyId" />-->
        <!--      <el-table-column label="是否删除" align="center" prop="isDelete" />-->
        <!--      <el-table-column label="状态，0：正常，1：禁用" align="center" prop="status" />-->
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              @click="UnbindCompany(scope.row)"
            >解除绑定
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>

import {
  bindStaff,
  bindStaffOnly,
  queryCarLeader,
  queryUser,
  listUser,
  UnbindStaff,
  bindAgent
} from "@/api/consumer/admin/driver";
import {dataScope} from "@/api/system/role";

export default {
  name: "User",
  dicts: ['c_user_role'],
  data() {
    return {
      // 遮罩层
      loading: true,
      dialogVisible: false, // 控制 dialog 的显示与隐藏s
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户账号表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        openid: null,
        userPhone: null,
        userNick: null,
        userHeader: null,
        userName: null,
        userRole: null,
        companyId: null,
        carId: null,
        walletPersonId: null,
        walletCompnyId: null,
        isDelete: null,
        status: null
      },
      // 表单参数
      form: {},
      driverForm: {
        name: '', // 用户姓名
        phone: '' // 手机号码
      },
      // 表单校验
      rules: {
        openid: [
          {required: true, message: "微信的openid号不能为空", trigger: "blur"}
        ],
      },
      userObject: {
        userId: '',        // 用户id
        userName: '',      // 用户姓名
        userPhone: '',     // 手机号码
        userNick: '',      // 昵称
        userHeader: '',    // 头像
        userRole: '',      // 角色
        companyName: ''    // 公司名称
      },

      driverLeaderObject: []
    };
  },
  created() {
    this.getList();
    this.clearUserObject();
  },
  methods: {
    dataScope,

    //直接绑定公司
    bindCompanyOnly: function () {
      const data = {
        userName: this.userObject.userName,
        userPhone: this.userObject.userPhone,
      }
      bindStaffOnly(data).then(response => {
        console.log(response.data);
        console.log('绑定公司成功');
        this.clearUserObject();
        this.$message.success('绑定公司成功'); // 显示成功提示
        this.getList();
      }).catch(error => {
        console.error('查询用户信息时出错:', error);
        this.clearUserObject();
        this.$message.error('绑定公司失败，请重试'); // 显示失败提示
      });
    },

    //弹出框
    showDialog() {
      queryCarLeader().then(response => {
        this.setDriverLeaderObject(response.data);
        this.driverLeaderObject = response.data;
        console.log('车队长信息:', response.data);
      }).catch(error => {
        console.error('查询车队长信息时出错:', error);
      });
      this.driverLeaderObject.userName = this.driverLeaderObject.userName;
      this.driverLeaderObject.userPhone = this.driverLeaderObject.userPhone;
      this.dialogVisible = true; // Show the dialog
    },
    // 绑定公司
    bindCompany: function (sysUserId) {
      console.log('绑定公司信息:', sysUserId.sysUserId);
      const data = {
        sysUserId: sysUserId.sysUserId,
        userName: this.userObject.userName,
        userPhone: this.userObject.userPhone,
      }

      console.log('绑定公司信息:', data);
      bindStaff(data).then(response => {
        console.log(response.data);
        this.$message.success('绑定公司成功'); // 显示成功提示
        this.clearUserObject();
        this.getList();
        console.log('绑定公司成功');
      }).catch(error => {
        console.error('查询用户信息时出错:', error);
        this.clearUserObject();
        this.$message.error('绑定公司失败，请重试'); // 显示失败提示
      });

    },
    // 解除绑定
    UnbindCompany: function (sysUserId) {
      console.log('解绑用户id:', sysUserId.userId);
      const data = {
        userId: sysUserId.userId,
      }

      console.log('绑定公司信息:', data);
      UnbindStaff(data).then(response => {
        console.log(response.data);
        this.$message.success('解除绑定成功'); // 显示成功提示
        console.log('解除绑定成功');
        this.getList();
      }).catch(error => {
        console.error('查询用户信息时出错:', error);
        this.$message.error('解除绑定失败，请重试'); // 显示失败提示
      });
    },

    //查找用户
    onSubmit: function () {
      this.clearUserObject();
      // 获取表单中输入的值
      const userName = this.driverForm.name;
      const phoneNumber = this.driverForm.phone;
      // 可以在这里对获取到的值进行处理或执行相应的操作
      console.log('用户姓名:', userName);
      console.log('手机号码:', phoneNumber);
      const data = {
        userName: userName,
        userPhone: phoneNumber
      };
      queryUser(data).then(response => {
        console.log(response.data);
        const userData = response.data;
        if (userData) {
          // 用户存在，存储到对象中
          this.setUserObject(userData);
          console.log('用户信息:', userData);
        } else {
          // 用户不存在，提示用户
          console.log('用户不存在');
        }
      }).catch(error => {
        console.error('查询用户信息时出错:', error);
      });
    },

    setUserObject(userData) {
      this.userObject.userId = userData.userId;
      this.userObject.userName = userData.userName;
      this.userObject.userPhone = userData.userPhone;
      this.userObject.userNick = userData.userNick;
      this.userObject.userHeader = userData.userHeader;
      this.userObject.userRole = userData.userRole;
      this.userObject.companyName = userData.companyName;
    },
    clearUserObject() {
      this.userObject = {
        userId: null,
        userName: null,
        userPhone: null,
        userNick: null,
        userHeader: null,
        userRole: null,
        companyName: null
      };
    },
    setDriverLeaderObject(driverLeaderData) {
      this.driverLeaderObject.userName = driverLeaderData.userName;
      this.driverLeaderObject.userPhone = driverLeaderData.userPhone;
      this.driverLeaderObject.sysUserId = driverLeaderData.sysUserId;
    },
    /** 查询用户账号列表 */
    getList: function () {
      this.loading = true;
      listUser().then(response => {
        this.userList = response.rows;
        console.log('用户列表:', response.rows);
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: null,
        openid: null,
        userPhone: null,
        userNick: null,
        userHeader: null,
        userName: null,
        userRole: null,
        companyId: null,
        carId: null,
        walletPersonId: null,
        walletCompnyId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDelete: null,
        status: null
      };
      this.resetForm("form");
    },
    // 指定业务员
    bindAgent: function (sysUserId) {
      console.log('绑定公司信息:', sysUserId.sysUserId);
      const data = {
        userName: this.userObject.userName,
        userPhone: this.userObject.userPhone,
        sysUserId: sysUserId.sysUserId,
      }

      console.log('绑定公司信息:', data);
      bindAgent(data).then(response => {
        console.log(response.data);
        this.$message.success('指定业务员成功'); // 显示成功提示
        this.getList();
        console.log('指定业务员成功');
      }).catch(error => {
        console.error('查询用户信息时出错:', error);
        this.$message.error('指定业务员失败，请重试'); // 显示失败提示
      });
    }
  }
};
</script>
<style scoped>
.search-form-container {
  display: flex;
}

.search-form {
  margin-left: 10px;
  flex: 1;
  max-width: 33.3%; /* 占据父元素的 1/3 宽度 */
  padding: 20px;
  box-sizing: border-box;
  border: 1px solid #ccc;
}

.user-info {
  margin-right: 10px;
  flex: 1;
  max-width: 66.6%; /* 占据父元素的 1/3 宽度 */
  padding: 20px;
  box-sizing: border-box;
  border: 1px solid #ccc;
}

.driver-list {
  margin-top: 10px;
  margin-right: 10px;
  margin-left: 10px;

}

</style>
